/**
 * 检测时间段是否包含深夜时间点
 * @param {dayjs} startTime - 开始时间(dayjs对象)
 * @param {dayjs} endTime - 结束时间(dayjs对象)
 * @returns {boolean} 如果时间段包含任何深夜时间点则返回true，否则返回false
 */

import dayjs from "dayjs";
import isBetween from "dayjs/plugin/isBetween";
dayjs.extend(isBetween);

const hasDeepNightTime = (startTime, endTime, DEEP_NIGHT_POINTS = null) => {
  if (!DEEP_NIGHT_POINTS) {
    // 全局深夜时间点数组，格式为"HH:mm"
    DEEP_NIGHT_POINTS = ["02:30", "04:00", "06:00"];
  }

  // 将时间点转换为从午夜开始的分钟数
  const nightPointsInMinutes = DEEP_NIGHT_POINTS.map((time) => {
    const [h, m] = time.split(":").map(Number);
    return h * 60 + m;
  });

  // 生成检查时间点（处理跨日情况）
  const checkPoints = [];
  const totalMinutes = endTime.diff(startTime, "minute");

  nightPointsInMinutes.forEach((minutes) => {
    // 计算第一个可能的时间点（当天）
    const basePoint = startTime.clone().startOf("day").add(minutes, "minute");

    // 如果basePoint早于startTime，则应该是下一天的该时间
    const firstValidPoint = basePoint.isBefore(startTime)
      ? basePoint.add(1, "day")
      : basePoint;

    // 添加所有在时间段内的时间点
    let currentPoint = firstValidPoint;
    while (currentPoint.isBefore(endTime)) {
      checkPoints.push(currentPoint);
      currentPoint = currentPoint.add(1, "day");
    }
  });

  // 检查是否有任何时间点落在区间内
  return checkPoints.some((point) =>
    point.isBetween(startTime, endTime, null, "[]")
  );
};

export default hasDeepNightTime;
